package com.xingkeduo.business.user.event;

import com.alibaba.fastjson.JSON;
import com.xingkeduo.business.user.feign.SendMsgFeign;
import com.xingkeduo.pojo.enums.SendingTypeEnum;
import com.xingkeduo.pojo.utils.MpUtils;
import com.xingkeduo.pojo.utils.ResponseUtils;
import com.xingkeduo.util.pojo.exception.DataException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 微信消息通知封装
 *
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/7/18 14:43
 **/
@Slf4j
@Service
public class EventHandleService {

    @Value("${profiles.active}")
    private String active;

    @Resource
    private SendMsgFeign sendMsgFeign;

    /**
     * @param sendingTypeEnum:事件类型
     * @param evenBaseDTO:         mpId不用传
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/7/18 16:39
     */
    public String eventHandle(SendingTypeEnum sendingTypeEnum, EvenBaseDTO evenBaseDTO) {
        log.info("请求参数sendingTypeEnum[{}],evenBaseDTO",sendingTypeEnum,JSON.toJSONString(evenBaseDTO));
        String res = null;
        evenBaseDTO.setMpId(MpUtils.checkGetMpId(active));
        if (sendingTypeEnum.equals(SendingTypeEnum.TEMPLATE)) {
            //发送模板消息
            log.info("发送模板消息");
        } else if (sendingTypeEnum.equals(SendingTypeEnum.OPEN_ID)) {
            //根据code获取openId
            log.info("根据code获取openId");
        } else if (sendingTypeEnum.equals(SendingTypeEnum.QR_CODE)) {
            //生成二维码ticket
            log.info("生成二维码");
        } else if (sendingTypeEnum.equals(SendingTypeEnum.MENU_BTN)) {
            //创建菜单按钮
            log.info("创建菜单按钮");
        } else if (sendingTypeEnum.equals(SendingTypeEnum.MSG_TEMP)) {
            //发送客服消息
            log.info("发送客服消息");
        } else {
            //扩展其他业务
            return null;
        }
        res = sendWechat(sendingTypeEnum.value(), evenBaseDTO);
        return res;
    }

    /**
     * 返回微信事件
     *
     * @param sendingType:发送类型
     * @param evenBaseDTO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/7/10 19:52
     */
    public String sendWechat(String sendingType, EvenBaseDTO evenBaseDTO) {
        ResponseUtils<String> responseUtils = null;
        try {
            responseUtils = sendMsgFeign.sendWechat(sendingType, evenBaseDTO);
        } catch (Throwable t) {
            FeignException.feignExceptionHandle(t);
        }
        if (responseUtils.success()) {
            String data = responseUtils.getData();
            log.info("data[{}]", data);
            return data;
        } else {
            log.info("获取微信事件[{}],参数失败[{}]", sendingType, JSON.toJSONString(evenBaseDTO));
            throw new DataException(DataException.Type.DEFAULT, sendingType + "返回失败");
        }
    }

}
